package com.hskn.hss.http;

import com.alibaba.fastjson.JSONObject;
import com.hskn.hss.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Component
public class HttpUtils {

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 生成post请求的JSON请求参数
     *
     * @return HttpEntity
     */
    private HttpEntity<Map<String, String>> generatePostJson(Map<String, String> jsonMap) {
        //如果需要其它的请求头信息、都可以在这里追加
        HttpHeaders httpHeaders = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
        httpHeaders.setContentType(type);
        HttpEntity<Map<String, String>> httpEntity = new HttpEntity<>(jsonMap, httpHeaders);
        return httpEntity;
    }

    /**
     * 生成get参数请求url
     *
     * @param url    请求的uri 示例: http://127.0.0.1:80
     * @param params 请求参数
     * @return String
     */
    private String generateRequestParameters(String url, Map<String, String> params) {
        StringBuilder sb = new StringBuilder(url);
        if (StringUtils.isNotEmpty(params)) {
            sb.append("?");
            for (Map.Entry map : params.entrySet()) {
                sb.append(map.getKey()).append("=").append(map.getValue()).append("&");
            }
            url = sb.substring(0, sb.length() - 1);
            return url;
        }
        return sb.toString();
    }

    /**
     * sendGet
     *
     * @param url url
     * @return String
     */
    public String sendGet(String url, Map<String, String> params) {
        ResponseEntity responseEntity = restTemplate.getForEntity(generateRequestParameters(url, params), String.class);
        return (String) responseEntity.getBody();
    }

    /**
     * post请求、请求参数为json
     *
     * @return String
     */
    public String sendPost(String url, Map<String, String> jsonMap) {
        ResponseEntity<String> apiResponse = restTemplate.postForEntity(url, generatePostJson(jsonMap), String.class);
        return apiResponse.getBody();
    }

    /**
     * post请求、请求参数为json
     *
     * @return String
     */
    public String sendPostBody(String url, JSONObject jsonBody) {
        ResponseEntity<String> apiResponse = restTemplate.postForEntity(url, jsonBody, String.class);
        return apiResponse.getBody();
    }

}

